import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'

export const formatChineseDate = (date: string | Date, format: string): string => {
  dayjs.locale('zh-cn')
  return dayjs(date).format(format)
}

export const formatDate = (date: string | Date, format = 'YYYY-MM-DD'): string => {
  return dayjs(date).format(format)
}

export const getCurrentYear = (): string => {
  return dayjs().format('YYYY')
}

export const getCurrentMonth = (): string => {
  return dayjs().format('YYYY-MM')
}

export const getMonthFirstDay = (date: string): Date => {
  return dayjs(date).startOf('month').toDate()
}

export const getStartEndDate = (date: string, dateType: 'month' | 'year'): string[] => {
  const format = 'YYYY-MM-DD'
  if (dateType === 'month') {
    return [dayjs(date).startOf('month').format(format), dayjs(date).endOf('month').format(format)]
  } else {
    return [dayjs(date).startOf('year').format(format), dayjs(date).endOf('year').format(format)]
  }
}

/**
 * 判断日期大小
 * @param startDate 开始日期
 * @param endDate 结束日期
 */
export const isBeforeDate = (startDate: Date | string, endDate: Date | string): boolean => {
  return dayjs(startDate).isBefore(endDate)
}

/**
 * 获取之前的日期
 * @param date 日期
 * @param amount 数量
 * @param unit 单位
 */
export const getLastDate = (date: Date | string, amount: number, unit: 'days' | 'months' | 'years'): string => {
  return dayjs(date).subtract(amount, unit).format('YYYY-MM-DD')
}

/**
 * 获取之后的日期
 * @param date 日期
 * @param amount 数量
 * @param unit 单位
 */
export const getNextDate = (date: Date | string, amount: number, unit: 'days' | 'months' | 'years'): string => {
  return dayjs(date).add(amount, unit).format('YYYY-MM-DD')
}

/**
 * @deprecated 获取前几天的日期
 * @param days 天数
 */
export const getLastDaysDate = (days: number): string => {
  return dayjs(new Date()).subtract(days, 'days').format('YYYY-MM-DD')
}

/**
 * @deprecated 获取上个月的日期
 * @param months 月数
 */
export const getLastMonthsDate = (months: number): string => {
  return dayjs(new Date()).subtract(months, 'months').format('YYYY-MM-DD')
}

/**
 * @deprecated 获取前几年的日期
 * @param years 天数
 */
export const getLastYearsDate = (years: number): string => {
  return dayjs(new Date()).subtract(years, 'years').format('YYYY-MM-DD')
}

/**
 * 获取两个日期间隔
 * @param startDate 开始日期
 * @param endDate 结束日期
 * @param unit 单位
 */
export const getDateDifference = (startDate: string, endDate: string, unit: 'days' | 'months' | 'years'): number => {
  return dayjs(endDate).diff(dayjs(startDate), unit)
}
